#include "carmainwindow.h"
#include "ui_carmainwindow.h"
#include <QDateTime>
#include <QDebug>
#include<QPixmap>
#include <QMessageBox>
#include "paymainwindow.h"
#include <QHostAddress>
#include <QFile>

const QString  baiduTokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%1&client_secret=%2&";
const char *client_id = "Fsmn51hMFUBNKhlZYh9ljG4l";
const char *secret_id = "KAEpEVjPgZ3SFcf8Wa00W93wVXMrhzEg";
const QString baiduImageUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=%1";


CarMainWindow::CarMainWindow(QWidget *parent) :
QMainWindow(parent),
    ui(new Ui::CarMainWindow)
{
    ui->setupUi(this);



    QPixmap pic(":/new/prefix1/icon/5.bmp");
    //根据显示控件的大小动态 调整 图片的大小
    pic = pic.scaled(ui->label_pic->size());
    ui->label_pic->setPixmap(pic);

    //得到当前时间
    tm = QTime::currentTime();
    ui->label_time->setText(tm.toString("hh:mm:ss"));
    connect(&m_timer,&QTimer::timeout,this,&CarMainWindow::onUpdateTime);
    m_timer.start(1);
    QDateTime datetime = QDateTime::currentDateTime();
    qDebug()<<datetime.toString();


    //数据库的初始化
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("car.db");
    if(!db.open())
    {
        qDebug()<<db.lastError().text();
        return ;
    }

    //muqian车辆信息表
    QString sql = QString("create table if not exists curInfo(carid text,enterTime text);");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<query.lastError().text();
        return ;
    }
    //历史车辆信息表
    sql = QString("create table if not exists recordInfo(carid text,enterTime text,lastTime text,sece text,money text);");

    if(!query.exec(sql))
    {
        qDebug()<<query.lastError().text();
        return ;
    }
    //vip车辆信息表
    sql = QString("create table if not exists vipInfo(carid text,enterTime text,lastTime text,sece text,money text);");

    if(!query.exec(sql))
    {
        qDebug()<<query.lastError().text();
        return ;
    }
    //表格控件的初始化

    //当前车辆 表格控件
    QStringList header;
    header<<"车牌号"<<"进场时间";


    ui->tableWidget->setColumnCount(2);

    for(int i=0; i<ui->tableWidget->columnCount(); i++)
    {
        QTableWidgetItem *item;
        //字段carid
        item = new QTableWidgetItem(header.at(i));

        //设置表头的样式
        QFont font = item->font();
        font.setBold(true);
        font.setPixelSize(20);
        item->setFont(font);
        //手动更改列宽
        ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
        //插到表格控件中
        ui->tableWidget->setHorizontalHeaderItem(i,item);
    }

    //历史车辆表格控件

    header<<"出场时间"<<"时长"<<"费用";

    ui->tableWidget_record->setColumnCount(5);

    for(int i=0; i<ui->tableWidget_record->columnCount(); i++)
    {
        QTableWidgetItem *item;
        //字段carid
        item = new QTableWidgetItem(header.at(i));

        //设置表头的样式
        QFont font = item->font();
        font.setBold(true);
        font.setPixelSize(20);
        item->setFont(font);
         ui->tableWidget_record->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
        ui->tableWidget_record->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

        //插到表格控件中
        ui->tableWidget_record->setHorizontalHeaderItem(i,item);
    }
    //vip车辆表格控件
    QStringList header1;
    header1<<"车牌号"<<"进场时间"<<"出场时间"<<"时长"<<"费用";

    ui->tableWidget_vip->setColumnCount(5);

    for(int i=0; i<ui->tableWidget_vip->columnCount(); i++)
    {
        QTableWidgetItem *item;
        //字段carid
        item = new QTableWidgetItem(header.at(i));

        //设置表头的样式
        QFont font = item->font();
        font.setBold(true);
        font.setPixelSize(20);
        item->setFont(font);


        ui->tableWidget_vip->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        //插到表格控件中
        ui->tableWidget_vip->setHorizontalHeaderItem(i,item);
    }


    //1、实例化一个TCP客户端类的对象
    m_tcpSocket = new QTcpSocket;
    //获取服务器的IP地址和端口号
    QString iP = QString("127.0.0.1");
    short port = 1234;
    //2、连接服务器
    m_tcpSocket->connectToHost(QHostAddress(iP),port);
    qDebug()<<"连接成功";
    //当连接成功的时候，会自动触发connected().,关联槽函数，确认连接成功
    connect(m_tcpSocket,&QTcpSocket::connected,this,&CarMainWindow::onConnected);


}

CarMainWindow::~CarMainWindow()
{
    delete ui;
}
//接收数据
void CarMainWindow::onConnected()
{
      qDebug()<<"-----------";
    //当连接成功了，如果服务器发送数据过来，会自动触发 readyRead信号，关联槽函数接收数据
    connect(m_tcpSocket,&QTcpSocket::readyRead,this,&CarMainWindow::onRecvDataSlot);
}
//接收服务器图片
void CarMainWindow::onRecvDataSlot()
{

 QByteArray ret= imgeData.append(m_tcpSocket->readAll());
 qDebug()<<ret.size();

     //显示
    QPixmap pix;
    pix.loadFromData(imgeData);
    pix =  pix.scaled(ui->label_pic->size());
    ui->label_pic->setPixmap(pix);

     QFile file("2.bmp");
     file.open(QIODevice::WriteOnly);
     file.write(imgeData);
     file.close();
if(imgeData.size()==921654)
{
    imgeData.clear();
    qDebug()<<imgeData.size();
}


}
//时间
void CarMainWindow::onUpdateTime()
{
    tm = tm.addMSecs(1);
    ui->label_time->setText(tm.toString("hh:mm:ss"));
}

//识别车牌
QString CarMainWindow::identifyCarid()
{
    QByteArray img = Image::imageToBase64("2.bmp");
    QByteArray imgData = "image=" + img; //body

    //获取access_token
    QByteArray replyData; //保存回复信息
    QString url = QString(baiduTokenUrl).arg(client_id).arg(secret_id);

    QMap<QString,QString> header; //封装头部信息
    header.insert(QString("Content-Type"),QString("application/x-www-form-urlencoded"));


    bool result = Http::post_syns(url,header,imgData,replyData);
    if(result)
    {
        QJsonObject obj = QJsonDocument::fromJson(replyData).object();

        accessToken = obj.value("access_token").toString();
    }


    replyData.clear();
    QString imgurl = baiduImageUrl.arg(accessToken);
    result = Http::post_syns(imgurl,header,imgData,replyData);
    if(result)
    {
        qDebug()<<"replyData:"<<replyData;

        QJsonObject obj = QJsonDocument::fromJson(replyData).object();
        QJsonValue val = obj.value("words_result");
        QString carId = val.toObject().value("number").toString();
        qDebug()<<"carId:"<<carId;

        return carId;
    }
    else{
          return "";
    }

}
//车辆进场
void CarMainWindow::on_btn_start_clicked()
{


        //进行识别
    QString carId = identifyCarid();
    if(carId.isEmpty())
    {
        ui->lineEdit->setText("failed");
        return ;
    }
    QPixmap  pimax =  QPixmap("2.bmp");
   pimax = pimax.scaled(ui->label_pic->size());
    ui->lineEdit->setText(carId);
    ui->label_pic->setPixmap(pimax);

    //3、标签控件上 提示 该车辆入库
    QString time = QDateTime::currentDateTime().toString();
    QString text = QString("当前车辆:%1 进入停车场\n停车时间:%2")
                            .arg(carId)
                            .arg(time);
   // ui->label_3->setText(text);

    //4、识别成功 入库操作
    QString sql = QString("insert into curInfo  values('%1','%2');")
                        .arg(carId)
                        .arg(time);

    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<query.lastError().text();
        return ;
    }

    //显示
    //新增一行
    int row = ui->tableWidget->rowCount();
    ui->tableWidget->setRowCount(row+1);
     ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);


    //carId
    QTableWidgetItem *item;
    item = new QTableWidgetItem(carId);
    ui->tableWidget->setItem(row,0,item);

    //time
    item = new QTableWidgetItem(time);
    ui->tableWidget->setItem(row,1,item);

}
//车辆离场
void CarMainWindow::on_btn_stop_clicked()
{
    //2、进行识别
   QString carId = identifyCarid();
    if(carId.isEmpty())
    {
        ui->lineEdit->setText("failed");
        return ;
    }

    ui->lineEdit->setText(carId);

    //3、遍历数据库的当前停车表信息，查找该车辆的入场时间
    QString sql = QString("select * from curInfo  where carid = '%1';")
                            .arg(carId);
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<query.lastError().text();
        return ;
    }
    //获取查询的结果
    QString enterTimeStr;//入场时间 -enterTime
    while(query.next())
    {
        enterTimeStr = query.value("enterTime").toString();
    }

    //计算时间差 --停车总时间  --以秒为单位
    QDateTime lastTime = QDateTime::currentDateTime();//出场时间
    //将入场时间 字符串 转换成  QDateTime
    QDateTime enterTime = QDateTime::fromString(enterTimeStr);
   int secs = enterTime.secsTo(lastTime);
    qDebug()<<"secs:"<<secs;
    int monovalent = ui->spinBox->text().toInt();
    double money = secs*monovalent;//计费



    //3、标签控件上 提示 该车辆出库
    QString text = QString("当前车辆:%1 开出停车场\n"
                           "进场时间:%2 出场时间:%3\n"
                           "停车总时长:%4秒 停车费用:%5")
                            .arg(carId)
                            .arg(enterTimeStr)
                            .arg(lastTime.toString())
                            .arg(secs)
                            .arg(money);
    //4、识别成功 入库操作
    QString sql1 = QString("insert into recordInfo  values('%1','%2','%3','%4',%5);").arg(carId)
            .arg(enterTimeStr)
            .arg(lastTime.toString())
            .arg(secs)
            .arg(money);

    QSqlQuery query1;
    if(!query1.exec(sql1))
    {
        qDebug()<<query1.lastError().text();
        return ;
    }

    //显示
    //新增一行
    int row = ui->tableWidget_record->rowCount();
    ui->tableWidget_record->setRowCount(row+1);
    ui->tableWidget_record->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);

    //carId
    QTableWidgetItem *item;
    item = new QTableWidgetItem(carId);
    ui->tableWidget_record->setItem(row,0,item);

    //enterTimeStr
    item = new QTableWidgetItem(enterTimeStr);
    ui->tableWidget_record->setItem(row,1,item);

    //lastTimeStr
    item = new QTableWidgetItem(lastTime.toString());
    ui->tableWidget_record->setItem(row,2,item);

    //secs
    item = new QTableWidgetItem(QString::number( secs));
    ui->tableWidget_record->setItem(row,3,item);
    qDebug()<<secs;

    //money
    item = new QTableWidgetItem(QString::number(money));
    ui->tableWidget_record->setItem(row,4,item);
    qDebug()<<money;

    QString sql2 = QString("select * from curInfo  where carid = '%1';")
                            .arg(carId);
    QSqlQuery query2;
    if(!query2.exec(sql2))
    {
        qDebug()<<query2.lastError().text();

    }
    QString DelId;//
    while(query.next())
    {
        DelId = query.value("carId").toString();
    }

    //int Delrow = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(DelId.toUInt());

    PayMainWindow *widget = new PayMainWindow(this);
    widget->setAttribute(Qt::WA_DeleteOnClose);
    widget->setData(carId,enterTimeStr,lastTime.toString(),secs,money);
    widget->setAttribute(Qt::WA_DeleteOnClose);
    widget->show(); //非模态显示


}
//发送数据进行拍照
void CarMainWindow::on_btn_start_2_clicked()
{
    //发送命令给摄像头进行抓拍
    //发送数据
    //1、先获取你要发送的数据
    QString data = "1";
    //2、调用接口 发送数据
    m_tcpSocket->write(data.toLocal8Bit().data());
    ui->lineEdit->clear();
//    QTimer::singleShot(10000,this,&CarMainWindow::on_btn_start_clicked);
}
//会员结账
void CarMainWindow::on_btn_stop_2_clicked()
{

    //2、进行识别
    QString carId = identifyCarid();
    if(carId.isEmpty())
    {
        ui->lineEdit->setText("failed");
        return ;
    }

    ui->lineEdit->setText(carId);

    //3、遍历数据库的当前停车表信息，查找该车辆的入场时间
    QString sql = QString("select * from curInfo  where carid = '%1';")
                            .arg(carId);
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<query.lastError().text();
        return ;
    }
    //获取查询的结果
    QString enterTimeStr;//入场时间 -enterTime
    while(query.next())
    {
        enterTimeStr = query.value("enterTime").toString();
    }

    //计算时间差 --停车总时间  --以秒为单位
    QDateTime lastTime = QDateTime::currentDateTime();//出场时间
    //将入场时间 字符串 转换成  QDateTime
    QDateTime enterTime = QDateTime::fromString(enterTimeStr);
   int secs = enterTime.secsTo(lastTime);
    qDebug()<<"secs:"<<secs;

    int monovalent = ui->spinBox->text().toInt();
    double vipmoney = secs*monovalent;//计费


    //3、标签控件上 提示 该车辆出库
    QString text = QString("当前车辆:%1 开出停车场\n"
                           "进场时间:%2 出场时间:%3\n"
                           "停车总时长:%4秒 停车费用:%5")
                            .arg(carId)
                            .arg(enterTimeStr)
                            .arg(lastTime.toString())
                            .arg(secs)
                            .arg(vipmoney);
    //4、识别成功 入库操作
    QString sql1 = QString("insert into  vipInfo values('%1','%2','%3','%4',%5);").arg(carId)
            .arg(enterTimeStr)
            .arg(lastTime.toString())
            .arg(secs)
            .arg(vipmoney);

    QSqlQuery query1;
    if(!query1.exec(sql1))
    {
        qDebug()<<query1.lastError().text();
        return ;
    }

    //显示
    //新增一行
    int row = ui->tableWidget_vip->rowCount();
    ui->tableWidget_vip->setRowCount(row+1);


    //carId
    QTableWidgetItem *item;
    item = new QTableWidgetItem(carId);
    ui->tableWidget_vip->setItem(row,0,item);

    //enterTimeStr
    item = new QTableWidgetItem(enterTimeStr);
    ui->tableWidget_vip->setItem(row,1,item);

    //lastTimeStr
    item = new QTableWidgetItem(lastTime.toString());
    ui->tableWidget_vip->setItem(row,2,item);

    //secs
    item = new QTableWidgetItem(QString::number( secs));
    ui->tableWidget_vip->setItem(row,3,item);


    //money
    item = new QTableWidgetItem(QString::number(vipmoney));
    ui->tableWidget_vip->setItem(row,4,item);


    QString sql2 = QString("select * from curInfo  where carid = '%1';")
                            .arg(carId);
    QSqlQuery query2;
    if(!query2.exec(sql2))
    {
        qDebug()<<query2.lastError().text();

    }
    QString DelId;//
    while(query.next())
    {
        DelId = query.value("carId").toString();
    }

    //int Delrow = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(DelId.toUInt());


    SetVipData *widget = new SetVipData(this);
    widget->setAttribute(Qt::WA_DeleteOnClose);
    widget->set_vip_data(carId,enterTimeStr,lastTime.toString(),secs,vipmoney);
    widget->setAttribute(Qt::WA_DeleteOnClose);
    widget->show(); //非模态显示

}
